import axios from '@/libs/api.request'
import Rsa from '@/libs/rsa.js'
import Aes from '@/libs/aes.js'

export const login = async ({ hotelCode, userName, password }) => {
  var publicKey = Rsa.getPublicKey()
  var result = await getFetchKey(publicKey)
  var fetchKeyData = result.data.result
  var aesKey = Rsa.decrypt(fetchKeyData)
  // 缓存aeskey
  localStorage.setItem('aesKey', aesKey)
  // 加密
  userName = Aes.encrypt(userName)
  password = Aes.encrypt(password)
  const data = {
    hotelCode,
    userName,
    password
  }

  return axios.request({
    url: 'login/login',
    data: data,
    method: 'post'
  })
}

export const getFetchKey = async (publicKey) => {
  return axios.request({
    url: 'generic/fetchKeyBase',
    headers: {
      mac: '909C4AC8E092;000EC6688070;00FF6CC8F7F8;005056C00001;005056C00008;147DDAB3A6E7',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      modulus: publicKey
    },
    method: 'post',
    transformRequest: [
      function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        ret = ret.substring(0, ret.lastIndexOf('&'))
        return ret
      }
    ]

  })
}

export const getUserInfo = (token) => {
  return axios.request({
    url: 'login/get_info',
    params: {
      token
    },
    method: 'get'
  })
}

export const logout = (token) => {
  return axios.request({
    url: 'login/logout',
    method: 'post'
  })
}

export const getUnreadCount = () => {
  return axios.request({
    url: 'message/count',
    method: 'get'
  })
}

export const getMessage = () => {
  return axios.request({
    url: 'message/init',
    method: 'get'
  })
}

export const getContentByMsgId = msg_id => {
  return axios.request({
    url: 'message/content',
    method: 'get',
    params: {
      msg_id
    }
  })
}

export const hasRead = msg_id => {
  return axios.request({
    url: 'message/has_read',
    method: 'post',
    data: {
      msg_id
    }
  })
}

export const removeReaded = msg_id => {
  return axios.request({
    url: 'message/remove_readed',
    method: 'post',
    data: {
      msg_id
    }
  })
}

export const restoreTrash = msg_id => {
  return axios.request({
    url: 'message/restore',
    method: 'post',
    data: {
      msg_id
    }
  })
}
